//
//  TabBarItemView.swift
//  TabBarView
//
//  Created by haisheng huang on 15/10/29.
//  Copyright © 2015年 huanghaisheng. All rights reserved.
//

import UIKit

/*样式*/
public enum TabItemStyle {
    case Title
    case TitleAndIcon
}

/*外键*/
//public let titleKey: String! = "TableItemInfoKeyTitle"
//let normalImageKey: String! = "TableItemInfoKeyNormalImage"
//let highlightedImageKey: String! = "TableItemInfoKeyHighlightedImage"
//let normalColorKey: String! = "TableItemInfoKeyNormalColor"
//let highlightedColorKey: String! = "TableItemInfoKeyHighlightedColor"

/*delegate*/
@objc public protocol TabBarItemViewDelegate: NSObjectProtocol {
    optional func shouldClickedTabBarItemView(view:TabBarItemView) -> Bool
    optional func didClickedTabBarItemView(view:TabBarItemView)
}

public class TabBarItemView: UIView {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
    
    var iconView: UIImageView?
    var titleLabel: UILabel?
    var button: UIButton?
    var highlightedImage: UIImage?
    var normalImage: UIImage!
    var title: String?
    var normalColor: UIColor?
    var highlightedColor: UIColor?
    var itemStyle: TabItemStyle?
    var delegate: TabBarItemViewDelegate?
    
    var iconSizeLength: CGFloat? = 24.0 //default 30.0
    var titleHeight: CGFloat? = 16.0 //default 16.0
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        self.delegate = nil
    }
    
    convenience init(frame: CGRect, itemInfo: NSDictionary?, itemStyle:TabItemStyle) {
        
        self.init(frame: frame)
        
        self.itemStyle = itemStyle
        self.title = itemInfo![TabItemInfoKeyTitle] as? String
        self.normalImage = self.getIconImage(itemInfo![TabItemInfoKeyNormalImage])
        self.highlightedImage = self.getIconImage(itemInfo![TabItemInfoKeyHighlightedImage])
        self.normalColor = self.getItemTextColor(itemInfo![TabItemInfoKeyNormalColor])
        self.highlightedColor = self.getItemTextColor(itemInfo![TabItemInfoKeyHighlightedColor])
        
        if itemStyle == TabItemStyle.Title {
            
            let button = UIButton(type: UIButtonType.Custom)
            button.frame.size = frame.size
            button.addTarget(self, action: "clickedTabBar:", forControlEvents: UIControlEvents.TouchUpInside)
            self.addSubview(button)
            self.button = button
            
            let titleLabel = UILabel()
            titleLabel.frame.size = frame.size
            titleLabel.font = UIFont.systemFontOfSize(17.0)
            titleLabel.textAlignment = NSTextAlignment.Center
            titleLabel.textColor = self.normalColor
            titleLabel.text = self.title
            self.addSubview(titleLabel)
            self.titleLabel = titleLabel
            
        } else if itemStyle == TabItemStyle.TitleAndIcon {
            
            let button = UIButton(type: UIButtonType.Custom)
            button.frame.size = frame.size
            button.addTarget(self, action: "clickedTabBar:", forControlEvents: UIControlEvents.TouchUpInside)
            self.addSubview(button)
            self.button = button
            
            let iconView = UIImageView()
            iconView.frame = CGRectMake(frame.width/2.0 - self.iconSizeLength!/2.0, (3.0+(30.0-self.iconSizeLength!)/2.0), self.iconSizeLength!, self.iconSizeLength!)
            iconView.image = self.normalImage
            self.addSubview(iconView)
            self.iconView = iconView
            
            let titleLabel = UILabel()
            titleLabel.frame = CGRectMake(0.0, frame.height - self.titleHeight!, frame.width, self.titleHeight!)
            titleLabel.font = UIFont.systemFontOfSize(11.0)
            titleLabel.textAlignment = NSTextAlignment.Center
            titleLabel.textColor = self.normalColor
            titleLabel.text = self.title
            self.addSubview(titleLabel)
            self.titleLabel = titleLabel
            
        }
        
    }
    
    override public func layoutSubviews() {
        super.layoutSubviews()
        let frame = self.frame
        if self.itemStyle == TabItemStyle.TitleAndIcon {
            self.button?.frame = CGRectMake(0.0, 0.0, frame.width, frame.height)
            self.iconView?.frame = CGRectMake(frame.width/2.0 - self.iconSizeLength!/2.0, (3.0+(30.0-self.iconSizeLength!)/2.0), self.iconSizeLength!, self.iconSizeLength!)
            self.titleLabel?.frame =  CGRectMake(0.0, frame.height - self.titleHeight!, frame.width, self.titleHeight!)
        } else if self.itemStyle == TabItemStyle.Title {
            self.button?.frame = CGRectMake(0.0, 0.0, frame.width, frame.height)
            self.titleLabel?.frame = CGRectMake(0.0, 0.0, frame.width, frame.height)
            
        }
    }
    
    /*设置item的正常状态*/
    func setNormalStatus() {
        self.titleLabel?.textColor = self.normalColor
        if self.itemStyle == TabItemStyle.TitleAndIcon && self.normalImage != nil {
            self.iconView?.image = self.normalImage
        }
    }
    
    /*设置item的高亮状态*/
    func setHighlightedStatus() {
        
        self.titleLabel?.textColor = self.highlightedColor
        if self.itemStyle == TabItemStyle.TitleAndIcon && self.highlightedImage != nil {
            self.iconView?.image = self.highlightedImage
        }
    }
    
    /*手动设置点击item*/
    func clickMe() {
        self.clickedTabBar(nil)
    }
    
    /*item button点击action*/
    func clickedTabBar(sender:UIButton?) {
        
        if ((self.delegate?.respondsToSelector("shouldClickedTabBarItemView:")) != nil) {
            if ((self.delegate?.shouldClickedTabBarItemView!(self)) != false) {
                self.setHighlightedStatus()
                self.delegate?.didClickedTabBarItemView!(self)
            }
        } else {
            self.setHighlightedStatus()
            self.delegate?.didClickedTabBarItemView!(self)
        }
    }
    
    /*获取icon image*/
    private func getIconImage(image:AnyObject?) -> UIImage? {
        if image is UIImage {
            return image as? UIImage
        } else if image is String {
            return UIImage(named: image as! String)
        } else {
            return nil
        }
    }
    
    /*获取颜色UIColor*/
    private func getItemTextColor(color:AnyObject?) -> UIColor? {
        if color is UIColor {
            return color as? UIColor
        } else if color is String {
            return self.colorWithHexString((color as? String)!)
        } else {
            return nil
        }
    }
    
    /*十六进制字符串转换UIColor*/
    private func colorWithHexString(stringToConvert:String) -> UIColor {
        
        var cString = stringToConvert.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).uppercaseString
        
        if cString.characters.count  < 6 {
            return UIColor.whiteColor()
        }
        
        if cString.hasPrefix("0X") {
            cString = cString.substringFromIndex(cString.characters.indexOf("X")!)
            //cString = (cString as NSString).substringFromIndex(2)
        }
        
        if cString .hasPrefix("#") {
            print("\(cString.characters.indexOf("#")!)")
            cString = cString.substringFromIndex(cString.startIndex.successor())
        }
        
        if cString.characters.count != 6 {
            return UIColor.whiteColor()
        }
        
        let rString = (cString as NSString).substringWithRange(NSMakeRange(0, 2))
        let gString = (cString as NSString).substringWithRange(NSMakeRange(2, 2))
        let bString = (cString as NSString).substringWithRange(NSMakeRange(4, 2))
        
        let r: Int = 0
        let g: Int = 0
        let b: Int = 0
        
        NSScanner(string: rString).scanHexInt(UnsafeMutablePointer(bitPattern: r))
        NSScanner(string: gString).scanHexInt(UnsafeMutablePointer(bitPattern: g))
        NSScanner(string: bString).scanHexInt(UnsafeMutablePointer(bitPattern: b))
        
        return UIColor(colorLiteralRed: float_t(r)/255.0, green: float_t(g)/255.0, blue: float_t(b)/255.0, alpha: 1.0)
        
    }
    
}
